package copyengine.resource.resProxy.cacheData
{
    import copyengine.log.CELog;
    import copyengine.utils.GeneralUtils;

    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.events.ProgressEvent;
    import flash.net.URLLoader;
    import flash.net.URLLoaderDataFormat;
    import flash.net.URLRequest;

    public class CEJsonResCacheData extends CEResCacheDataBasic
    {
        private var mURLLoader:URLLoader;
        private var mJSONObj:Object;

        public function CEJsonResCacheData()
        {
        }

        override protected function doLoadRes():void
        {
            mURLLoader = new URLLoader();
            mURLLoader.dataFormat = URLLoaderDataFormat.TEXT;
            addListener();
            mURLLoader.load(new URLRequest(mFileDesc.filePath));
        }

        override public function getData():* {return mJSONObj;}

        private function addListener():void
        {
            GeneralUtils.addTargetEventListener(mURLLoader, Event.COMPLETE, onLoaded);
            GeneralUtils.addTargetEventListener(mURLLoader, ProgressEvent.PROGRESS, onLoadInProgress);
            GeneralUtils.addTargetEventListener(mURLLoader, IOErrorEvent.IO_ERROR, onLoadInError);
        }

        private function removeListener():void
        {
            GeneralUtils.removeTargetEventListener(mURLLoader, Event.COMPLETE, onLoaded);
            GeneralUtils.removeTargetEventListener(mURLLoader, ProgressEvent.PROGRESS, onLoadInProgress);
            GeneralUtils.removeTargetEventListener(mURLLoader, IOErrorEvent.IO_ERROR, onLoadInError);
        }

        private function onLoaded(e:Event):void
        {
            var jsonSTR:String = mURLLoader.data as String;
            mJSONObj = JSON.parse(jsonSTR);
            removeListener();
            onResLoadComplete();
            //Loader资源可以释放掉
            mURLLoader = null;
        }


        private function onLoadInProgress(e:ProgressEvent):void {}

        private function onLoadInError(e:IOErrorEvent):void
        {
            removeListener();
            CELog.err(e.toString());
            CELog.err("CEJsonResCacheData-> load file in error, file: " + mFileDesc.toString());
        }
    }
}
